/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.great.functionalCore;

import br.great.beans.PossibleTag;
import com.mapia.Json.JSONException;
import com.mapia.Json.JSONObject;
import com.mapia.Json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class Wikimapia
{
    
	public static ArrayList<PossibleTag> Wikimapia(double lat, double lon) throws JSONException
{
    
    double lat_min, lat_max, lon_min, lon_max;  
    ArrayList<PossibleTag> apt = new ArrayList<PossibleTag>();
    PossibleTag pt = new PossibleTag();
  
    lat_min = lat-0.001;
    lat_max = lat+0.001;
    lon_min = lon-0.001;
    lon_max = lon+0.001;

String addr = "http://api.wikimapia.org/?function=box&lon_min=" + lon_min + "&lat_min=" + lat_min + "&lon_max=" + lon_max + "&lat_max=" + lat_max + "&key=D5BC6D38-6328FE-6DCB35B4-9A1A62F5-7E2DE01A-D12480C8-577904C0-309DEF33&format=json&count=10";
    try{
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
JSONTokener primary = new JSONTokener(reader);
JSONObject locals = new JSONObject(primary);
int loc = locals.getJSONArray("folder").length();
ArrayList<String> names = new ArrayList<String>();
for(int i=0; i<loc; i++)
        {
            names.add(locals.getJSONArray("folder").getJSONObject(i).getString("name"));
            String[] local = names.get(i).split("(?<=\\G.{1})");
            int c = local.length;
            if(")".equals(local[c-1])){
                String location = local[0];
                for(int j=1; j<c-5; j++)
                {
                    location += local[j];
                }
                pt.setValue(location);
                System.out.println(locals.getJSONArray("folder").getJSONObject(i));}
            else{
                String location = names.get(i);
                pt.setValue(location);
                System.out.println(locals.getJSONArray("folder").getJSONObject(i));
            }
            pt.setSufix("LOCATION");
            pt.setPrecision(1);
            apt.add(pt);
            pt = new PossibleTag();
        }



conn.disconnect();
}catch(IOException ex)
{
ex.printStackTrace();
System.out.println("made it here");
}

    return apt;
                
    }
	
        
      
}
